import { diffTimes, formatMinToHourMin } from '@/utils/utils';
import {
  ProCard,
  ModalForm,
  ProFormDateTimePicker,
  ProFormSwitch,
} from '@ant-design/pro-components';
import { message } from 'antd';
import type moment from 'moment';
import { useState } from 'react';
import { testChargeRule } from '../service';
import type { ChargeRuleTableItem } from '../types.d';
import RulesDetail from './RulesDetail';

const TestChargeRule = (props: {
  currItem: ChargeRuleTableItem;
  visible: boolean;
  setUnvisible: () => void;
}) => {
  const { visible, setUnvisible, currItem } = props;
  const [inTime, setInTime] = useState<string>('');
  const [outTime, setOutTime] = useState<string>('');
  const [frameParams, setFrameParams] = useState<{
    day: number;
    frame: number;
  }>({
    day: 0,
    frame: 0,
  });
  const [isLarge, setIsLarge] = useState<boolean>(false);
  const [fee, setFee] = useState<number>(0);

  return (
    <ModalForm
      title="收费规则核验"
      width={820}
      visible={visible}
      layout="inline"
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        onCancel: () => {
          setUnvisible();
        },
        okText: '计算',
        cancelText: '关闭',
      }}
      onFinish={async () => {
        const res = await testChargeRule({
          inTime: new Date(inTime),
          outTime: new Date(outTime),
          id: currItem._id,
          isLarge: isLarge,
        });
        if (!res.success) {
          message.error({
            content: res.message,
            key: 'test_chargeRule',
          });
          return false;
        }
        const { frameObj, amount } = res.data;
        setFrameParams(frameObj);
        setFee(amount);
        return false;
      }}
    >
      <ProCard
        size="small"
        direction="row"
        bodyStyle={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        <ProFormDateTimePicker
          label="驶入时间"
          placeholder="请选择驶入时间"
          name="inTime"
          fieldProps={{
            onChange: (value) => {
              const str = value?.format('YYYY-MM-DD HH:mm:ss') || '';
              setInTime(str);
            },
          }}
        />
        <ProFormDateTimePicker
          label="驶出时间"
          placeholder="请选择驶出时间"
          name="outTime"
          rules={[
            {
              validator: (_, value: moment.Moment) => {
                if (!value || !inTime) return Promise.resolve(value);
                const outN = value.valueOf();
                if (outN < new Date(inTime).getTime()) {
                  return Promise.reject(new Error('驶出时间需要大于驶入时间'));
                }
                return Promise.resolve(value);
              },
            },
          ]}
          fieldProps={{
            onChange: (value) => {
              const str = value?.format('YYYY-MM-DD HH:mm:ss') || '';
              setOutTime(str);
            },
          }}
        />
        <ProFormSwitch
          fieldProps={{
            onChange: () => {
              setIsLarge(!isLarge);
            },
            checked: isLarge,
          }}
          checkedChildren="大型车"
          unCheckedChildren="小型车"
        />
      </ProCard>

      <RulesDetail chargeRule={currItem} />
      <ProCard title="计费结果" size="small">
        <div>本次停车时长：{outTime && inTime ? diffTimes(outTime, inTime) : '0 分钟'}</div>
        <div>
          本次计费时长：{frameParams.day ? `${frameParams.day}天` : ''}
          {formatMinToHourMin(frameParams.frame)}
        </div>
        <div>本次停车费用：{(fee / 100).toFixed(2)} 元</div>
      </ProCard>
    </ModalForm>
  );
};

export default TestChargeRule;
